<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>验证码</title>
    <style type="text/css">
        .form-group {
            display: flex;
            align-items: center;
        }
        .form-group input[type="text"] {
            margin-right: 10px;
        }
        .verify-code-images {
            display: flex;
            align-items: center;
        }
        .verify-code-images img {
            width: 30px;
            height: 30px;
            margin-right: 5px;
        }
    </style>
    <script type="text/javascript">
        function generateVerifyCode() {
            var code = '';
            var imagesContainer = document.getElementById('verifyCodeImages');
            imagesContainer.innerHTML = ''; // 清空之前的图片
            for (var i = 0; i < 4; i++) {
                var digit = Math.floor(Math.random() * 10);
                code += digit;
                var img = document.createElement('img');
                img.src = 'img/' + digit + '.png';
                img.alt = digit;
                img.style.marginRight = '5px';
                imagesContainer.appendChild(img);
            }
            document.getElementById('hiddenVerifyCode').value = code;
        }

        function validateForm() {
            var userCode = document.forms["verifyForm"]["code"].value;
            var hiddenCode = document.getElementById('hiddenVerifyCode').value;
            if (userCode == "") {
                alert("请输入验证码");
                return false;
            }
            if (userCode !== hiddenCode) {
                alert("验证码错误，请重新输入");
                generateVerifyCode(); // 重新生成验证码
                document.forms["verifyForm"]["code"].value = '';
                return false;
            }
            return true;
        }

        window.onload　 = function() {
            generateVerifyCode();

            var message = '<%= request.getAttribute("message") %>';
            if (message) {
                alert(message);
            }
        };
    </script>
</head>
<body>
<form name="verifyForm" action="hello-servlet" method="post" onsubmit　="return validateForm()">
    <div class="form-group">
        验证码：<input type="text" name="code">
        <input type="hidden" id="hiddenVerifyCode" name="hiddenVerifyCode">
        <div id="verifyCodeImages" class="verify-code-images"></div>
    </div>
    <input type="submit" value="提交" style="margin-left: 120px; margin-top: 10px ">
</form>
</body>
</html>